import React, { useEffect, useState } from 'react'
import { useLocation, useNavigate } from "react-router-dom";

import { Badge, TabBar } from 'antd-mobile'
import { Outlet } from 'react-router-dom'
import { AppOutline, MessageOutline, UnorderedListOutline, UserOutline, } from 'antd-mobile-icons'

import styles from './index.module.css'

import { jumpTo } from '../../jump'

import { useDispatch, useSelector } from "react-redux";
import { increment, updateUser } from "../../redux/sliceTbale";


function Main(props) {

    let { pathname } = useLocation();
    let navigate = useNavigate()

    //分发
    let dispatch = useDispatch()
    //获取
    const counter = useSelector(state => state.mySlice.counter)
    //console.log('mian页面-useSelector-counter:', counter);
    const user = useSelector(state => state.mySlice.user)
    //console.log('mian页面-useSelector-user:', user);




    const [activeKey, setActiveKey] = useState('home')

    const tabs =
        [
            {
                key: 'home', title: '首页', icon: <AppOutline />, badge: Badge.dot,
            },

            {
                key: 'todo', title: '待办', icon: <UnorderedListOutline />, badge: '5',
            },

            {
                key: 'message', title: '消息', icon: <MessageOutline />, badge: '99+',
            },

            {
                key: 'personalCenter', title: '我的', icon: <UserOutline />,
            },
        ]


    //[]空数组相当于componentDidMount
    useEffect(() => {
        //用户刷新或者点击后退的时候或者首页进来的时候 保证tab指示条的准确性
        console.log('Main页面-路由变化了：', pathname)
        if (pathname.indexOf("home") !== -1) {
            //说明在home页面
            setActiveKey("home")
            document.title = '首页';
        } else if (pathname.indexOf("todo") !== -1) {
            setActiveKey("todo")
            document.title = '待办';
        } else if (pathname.indexOf("message") !== -1) {
            setActiveKey("message")
            document.title = '消息';
        } else if (pathname.indexOf("personalCenter") !== -1) {
            document.title = '我的';
            setActiveKey("personalCenter")
        }
        return () => {


        }
    }, [pathname]);

    function setRouteActive(value) {
        //用replace，替换当前栈顶的记录
        //navigate('/main/' + value, { replace: true, state: { params: 1 } } )
        const paras = { aaa: '这是参数1', bbb: '这是参数2' }
        jumpTo(navigate, '/main/' + value, true, paras)
        setActiveKey(value)
        //测试分发
        dispatch(increment(300))
        dispatch(updateUser({ job: '自由职业者' }))
    }

    //渲染组件
    return (<div className={styles.app}>
        <div className={styles.body}>
            <Outlet></Outlet>
        </div>
        <div className={styles.bottom}>
            <TabBar activeKey={activeKey} onChange={setRouteActive}>
                {tabs.map(item => (<TabBar.Item key={item.key} icon={item.icon} title={item.title} />))}
            </TabBar>
        </div>
    </div>)
}

export default Main;
